package com.woniuxy.learnmap.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.woniuxy.commons.dto.LearnMapDetailDto;
import com.woniuxy.commons.dto.LearnMapDto;
import com.woniuxy.commons.entity.LearnMap;
import com.woniuxy.commons.entity.LearnMapDetail;
import com.woniuxy.commons.entity.LearnMapDetailRecord;
import com.woniuxy.commons.entity.PageBean;
import com.woniuxy.commons.exception.EtmsServiceException;
import com.woniuxy.commons.exception.learnmap.LearnMapDetailRecordAlReadyExistException;
import com.woniuxy.commons.exception.learnmap.LearnMapNameAlReadyExistException;
import com.woniuxy.commons.exception.learnmap.NoImageException;
import com.woniuxy.learnmap.configuration.AliYunOSSConfiguration;
import com.woniuxy.learnmap.mapper.LearnMapDetailMapper;
import com.woniuxy.learnmap.mapper.LearnMapDetailRecordMapper;
import com.woniuxy.learnmap.mapper.LearnMapMapper;
import com.woniuxy.learnmap.service.LearnMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: 王敞
 * @E-mail： 365799712@qq.com
 * @Date: 2020/07/17/12:11
 * @Description: 学习地图service实现类
 */
@Service
public class LearnMapServiceImpl implements LearnMapService {
    @Autowired
    private LearnMapMapper learnMapMapper;
    @Autowired
    private LearnMapDetailMapper learnMapDetailMapper;
    @Autowired
    private LearnMapDetailRecordMapper learnMapDetailRecordMapper;

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private AliYunOSSConfiguration aliYunOSSConfiguration;

    @Override
    public void addLearnMap(LearnMap learnMap, List<LearnMapDetailDto> learnMapDetailDtos) {
        try {
            //先通过学习地图名判断改名字是否已经被使用
            LearnMap learnMap1 = learnMapMapper.findLearnMapByName(learnMap.getName());
            if (learnMap1 != null) {
                throw new LearnMapNameAlReadyExistException("该学习地图名字已被使用");
            }
            //再通过学习地图详情记录判断该学习地图组合是否已被使用
            String recordName = "";
            for (LearnMapDetailDto learnMapDetail : learnMapDetailDtos) {
                recordName += learnMapDetail.getOrderno() + learnMapDetail.getRouteid();
            }
            LearnMapDetailRecord record = learnMapDetailRecordMapper.findLMDRecord(recordName);
            if (record != null) {
                throw new LearnMapDetailRecordAlReadyExistException("该学习地图详情组合已被使用");
            }
            //新增学习地图
            learnMapMapper.addLearnMap(learnMap);
            //获取该学习地图的id
            LearnMap learnMap2 = learnMapMapper.findLearnMapByName(learnMap.getName());
            int lmid = learnMap2.getId();

            //所有的学习地图详情添加该学习地图id并增加到表中
            for (LearnMapDetailDto learnMapDetail : learnMapDetailDtos) {
                learnMapDetail.setLmid(lmid);
                learnMapDetailMapper.addLearnMapDetail(learnMapDetail);
            }
            //新增学习地图详情记录
            LearnMapDetailRecord learnMapDetailRecord = new LearnMapDetailRecord();
            learnMapDetailRecord.setRecordName(recordName).setStatus("1");
            learnMapDetailRecordMapper.addLMDRecord(learnMapDetailRecord);
        } catch (Exception e) {
            e.printStackTrace();
            throw new EtmsServiceException("系统维护中", e);
        }
    }

    /*
     *
     * @Description: 上传学习地图背景图片
     * @Param: [multipartFile]
     * @return: java.lang.String
     * @Author: 王敞
     * @Date: 16:06 2020/7/23
     **/
    @Override
    public String uploadImage(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        String type = fileName.substring(index);

        // 允许上传的格式
        String[] imageTypes = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
        //先对上传文件的格式进行校验，判断是否为图片
        boolean flag = false;
        for (String imageType : imageTypes) {
            if (imageType.equals(type)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new NoImageException("只能上传图片格式的文件");
        }
        //获取整个文件名
        fileName = UUID.randomUUID().toString() + type;
        //存储到阿里云
        String filePath = "lmimage/" + fileName;
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(getcontentType(type));
        try {
            ossClient.putObject(aliYunOSSConfiguration.getBucketName(),
                    filePath, new ByteArrayInputStream(file.getBytes()), meta);
            String url = aliYunOSSConfiguration.getUrlPrefix() + filePath;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            throw new EtmsServiceException("系统维护中，暂时无法双穿图片");
        }


    }

    /*
     *
     * @Description: 分页查询学习地图
     * @Param: [page, pageSize]
     * @return: com.woniuxy.commons.entity.PageBean<java.util.List<com.woniuxy.commons.dto.LearnMapDto>>
     * @Author: 王敞
     * @Date: 15:24 2020/7/25
     **/
    @Override
    public PageBean<LearnMapDto> findLearnMapsByPage(int page, int pageSize) {
        try {
            System.out.println(page);
            int index = (page - 1) * pageSize;
            List<LearnMapDto> learnMapDtos = learnMapMapper.findLearnMapsByPage(index, pageSize);
            int totalNums = learnMapMapper.findTotalNumsOfMaps();
            int totalPage = totalNums % pageSize == 0 ? totalNums / pageSize : totalNums / pageSize + 1;
            PageBean<LearnMapDto> pb = new PageBean<>();
            pb.setData(learnMapDtos).setNumsOfCurrPage(learnMapDtos.size()).setPage(page)
                    .setPageSize(pageSize).setTotalNum(totalNums).setTotalPage(totalPage);
            return pb;
        }catch(Exception e){
            e.printStackTrace();
            throw new EtmsServiceException("系统维护中");
        }
    }
    /*
    *
     * @Description: 通过学习地图id查询相关的学习地图详情
     * @Param: [lmid]
     * @return: java.util.List<com.woniuxy.commons.dto.LearnMapDetailDto>
     * @Author: 王敞
     * @Date: 9:50 2020/8/3
     **/
    @Override
    public List<LearnMapDetailDto> findLearnMapDetailByLMId(int lmid) {
        try{
            return learnMapDetailMapper.findLearnMapDetailByLMId(lmid);
        }catch (Exception e){
            e.printStackTrace();
            throw new EtmsServiceException("系统维护中");
        }
    }

    @Override
    public void del(int id) {
        try {
            learnMapMapper.del(id);
        }catch (Exception e){
            throw new EtmsServiceException("系统维护中");
        }
    }

    /*
     *
     * @Description: 根据上传文件类型设定上传到阿里云的格式
     * @Param: [type]
     * @return: java.lang.String
     * @Author: 王敞
     * @Date: 15:13 2020/7/24
     **/
    public static String getcontentType(String type) {
        if (type.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (type.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (type.equalsIgnoreCase(".jpeg") ||
                type.equalsIgnoreCase(".jpg") ||
                type.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (type.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (type.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (type.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (type.equalsIgnoreCase(".pptx") ||
                type.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (type.equalsIgnoreCase(".docx") ||
                type.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (type.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
